package model.behaviors;

import java.awt.Graphics2D;
import java.util.HashMap;
import java.util.List;
import model.Figure;
import model.Move;
import figures.Imgs;

/**
 * the bishop behavior
 */
public class Bishop extends AbstractBehavior {

    /**
     * the constructor of this figure behavior
     * 
     * @param color
     *            the color to choose the right figure
     */
    public Bishop( int color )
    {
	super();

	if ( color == Figure.WHITE )
	{
	    this.img = Imgs.BISHOP_W;
	}
	else
	{
	    this.img = Imgs.BISHOP_B;
	}
    }

    @Override
    public final void detectPossibleMoves( int fs, Graphics2D g, HashMap<String, Figure> figMap, Figure figure,
	    List<Move> movesList )
    {
	// empty list of valid fields
	this.validFields.clear();

	// calc x/y
	int x = figure.getX();
	int y = figure.getY();

	// up left
	for ( int i = 1; i < 8; i++ )
	{
	    if ( !checkJumpFields( x - i, y - i, figMap, figure ) )
	    {
		break;
	    }
	}

	// up right
	for ( int i = 1; i < 8; i++ )
	{
	    if ( !checkJumpFields( x + i, y - i, figMap, figure ) )
	    {
		break;
	    }
	}

	// down right
	for ( int i = 1; i < 8; i++ )
	{
	    if ( !checkJumpFields( x + i, y + i, figMap, figure ) )
	    {
		break;
	    }
	}

	// down left
	for ( int i = 1; i < 8; i++ )
	{
	    if ( !checkJumpFields( x - i, y + i, figMap, figure ) )
	    {
		break;
	    }
	}

	// end
	this.drawFields( fs, g );
    }

    /**
     * checks if the jump to a certain field is valid
     * 
     * @param x
     *            horizontal position
     * @param y
     *            vertical position
     * @param figMap
     *            reference to list of figures
     * @param figure
     *            reference to this figure object
     * @return TODO true if the jump is a certain field, false if not
     */
    private boolean checkJumpFields( int x, int y, HashMap<String, Figure> figMap, Figure figure )
    {
	boolean ret = false;
	// still on the board?
	if ( x >= 0 && x <= 7 && y >= 0 && y <= 7 )
	{
	    // empty field?
	    if ( figMap.get( convertXYToField( x, y ) ) == null )
	    {
		this.addToValidFields( x, y );
		ret = true;
	    }
	    // .. or enemy figure?
	    else if ( figMap.get( convertXYToField( x, y ) ).getColor() != figure.getColor() )
	    {
		this.addToValidFields( x, y );
	    }
	}
	return ret;
    }
}